package com.biz.primus.ms.commodity.service.backend;

import com.biz.primus.base.enums.SaleChannel;
import com.biz.primus.common.utils.ValueUtils;
import com.biz.primus.ms.base.service.AbstractBaseService;
import com.biz.primus.ms.commodity.dao.po.Brand;
import com.biz.primus.ms.commodity.dao.po.Category;
import com.biz.primus.ms.commodity.dao.redis.BrandRedisDao;
import com.biz.primus.ms.commodity.dao.repository.brand.BrandRepository;
import com.biz.primus.ms.commodity.trans.Brand2BrandRo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 品牌Service抽象类
 *
 * @author david-liu
 * @date 2017年01月24日
 * @reviewer
 */
public class AbstractBrandService extends AbstractBaseService {

    @Autowired
    protected BrandRepository brandRepository;

    @Autowired
    private BrandRedisDao brandRedisDao;

    protected void saveBrand(Brand brand) {
        this.saveOrUpdateUsingPo(brandRepository, brandRedisDao, brand, new Brand2BrandRo());
        //通过渠道控制是否显示在前端
        List<Long> categoryIds = brand.getCategories().stream().map(Category::getId).collect(Collectors.toList());
        if (brand.getSaleChannel() == SaleChannel.ALL || brand.getSaleChannel() == SaleChannel.APP) {
            this.delayer.executeAfterTransactionCommit(() -> brandRedisDao.setAppBrandSort(brand.getId(), categoryIds,
                    Double.valueOf(ValueUtils.getValue(brand.getId()))));
        } else if (brand.getSaleChannel() == null || brand.getSaleChannel() == SaleChannel.WEB) {
            this.delayer.executeAfterTransactionCommit(() -> brandRedisDao.removeAppSort(brand.getId(), categoryIds));
        }
    }

    protected void saveBrands(Iterable<Brand> brands) {
        for (Brand brand : brands) {
            this.saveBrand(brand);
        }
    }

}
